import axios from 'axios'
import { BaseRes, post } from '../libs/request'
import { IArticle, IComment } from '../types'

interface If extends BaseRes {
  result: boolean
}

interface Detail extends BaseRes {
  data: IArticle[]
}

interface Comments extends BaseRes {
  rows: IComment[]
}

interface Articles extends BaseRes {
  rows: IArticle[]
}

interface Key extends BaseRes {
  data: string
}

// 查看是否已赞
export async function findLike(articleId: string, token?: string) {
  const res = await post<If>('/api/article/like/find', { articleId }, token)
  return res.data
}

// 点赞、取消赞
export async function like(
  articleId: string,
  state: boolean,
  articleName: string
) {
  const res = await post<BaseRes>('/api/article/like', {
    state,
    articleId,
    articleName
  })
  return res.data
}

// 评论列表
export async function comments(articleId: string) {
  const res = await post<Comments>('/api/article/comments', { articleId })
  return res.data
}

// 发布评论
export async function comment(articleId: string, content: string) {
  const res = await post<BaseRes>('/api/article/comment', {
    articleId,
    content
  })
  return res.data
}

// 浏览
export async function view(articleId: string) {
  const res = await post<BaseRes>('/api/article/view', { articleId })
  return res.data
}

// 删除评论
export async function removeComment(id: string) {
  const res = await post<BaseRes>('/api/article/removeComment', { id })
  return res.data
}

// 发布文章
export async function postArticle(
  title: string,
  content: string,
  label: string[],
  banner?: string[]
) {
  const res = await post<BaseRes>('/api/article/post', {
    title,
    content,
    label,
    banner
  })
  return res.data
}

// 删除文章
export async function remove(id: string) {
  const res = await post<BaseRes>('/api/article/remove', { id })
  return res.data
}

// 搜索文章
export async function search(str: string) {
  const res = await post<Articles>('/api/article/search', { str })
  return res.data
}

// 文章详情
export async function detail(id: string) {
  const res = await post<Detail>('/api/article/detail', { id })
  return res.data
}

// 编辑详情
export async function edit(
  _id: string,
  title: string,
  content: string,
  label: string[],
  banner: string[],
  token?: string
) {
  const res = await post<Detail>(
    '/api/article/edit',
    { _id, title, content, label, banner },
    token
  )
  return res.data
}

// 图片上传
export async function upload(file: File) {
  const data = new FormData()
  data.append('file', file)
  const result = await axios.post<Key>('/api/article/upload', data)
  return result.data
}

// 图片下载
export async function keep(key: string) {
  const result = await axios.post('/api/article/download', { key })
  return result.data
}
